package com.atguigu.tingshu.album.init;

import com.atguigu.tingshu.album.mapper.AlbumInfoMapper;
import com.atguigu.tingshu.model.album.AlbumInfo;
import jakarta.annotation.PostConstruct;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Log4j2
public class RabbitConfirmAndReturnInit implements RabbitTemplate.ReturnsCallback,RabbitTemplate.ConfirmCallback {
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    AlbumInfoMapper albumInfoMapper;
    @PostConstruct
    public void init(){
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setConfirmCallback(this::confirm);
        rabbitTemplate.setReturnsCallback(this::returnedMessage);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        //获取消息
        ReturnedMessage returned = correlationData.getReturned();
        //获取消息内容
        String albumId = new String(returned.getMessage().getBody());
        //获取routingKey
        String routingKey = returned.getRoutingKey();

        if(!b){
            //兜底处理
            markFailInfo(albumId);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        Message message = returnedMessage.getMessage();
//        String exchange = returnedMessage.getExchange();
//        String routingKey = returnedMessage.getRoutingKey();
//        int replyCode = returnedMessage.getReplyCode();
//        String replyText = returnedMessage.getReplyText();
        String albumId = new String(message.getBody());
        //兜底
        markFailInfo(albumId);
    }

    /**
     * 消息兜底处理，专辑处理最终应该是什么状态是否和当前routingKey一致
     * @param albumId
     */
    private void markFailInfo(String albumId) {
        //查询数据库最终状态
//        AlbumInfo albumInfo = albumInfoMapper.selectById(albumId);
//        String status = albumInfo.getIsOpen().equals(1) ? "album.es.upper" : "album.es.down";
//        if (status.equals(routingKey)) {
//            //
//        }
//        redisTemplate.opsForHash().increment("album_up_or_down", albumId,1);
        redisTemplate.opsForSet().add("album_up_or_down",albumId);
    }
}
